package com.mingxun.project.http;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;


import com.mingxun.project.MyApplication;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;

/**
 * class name：头部信息辅助类
 *
 * @author liuhongyuan.
 * @date 2017/12/19
 */

public class TokenHeaderHelper {

	private final static String TOKEN_VALUE = "token_value";
	private final static String TOKEN_VALUE_FILE = "token_value_file";
	private SharedPreferences sharedPref;
	private PackageInfo packageInfo;
	private ApplicationInfo appInfo;

	public void saveToken(String token) {
		sharedPref.edit().putString(TOKEN_VALUE, token).apply();
	}

	public String readToken() {
		return sharedPref.getString(TOKEN_VALUE, "");
	}

	public void saveHeaderInfo(String deviceId,
	                           String deviceModel,
	                           String sysVersion,
	                           String appVersion,
	                           String channel,
								String deviceVersion) {
		sharedPref.edit().putString("deviceId", deviceId)
				.putString("deviceModel", deviceModel)
				.putString("sysVersion", sysVersion)
				.putString("appVersion", appVersion)
				.putString("channel", channel)
				.putString("source", "android")
				.putString("version",deviceVersion)
				.apply();
	}

	public String getDeviceId() {
		return sharedPref.getString("deviceId", "");
	}

	public String getDeviceModel() {
		return sharedPref.getString("deviceModel", "");
	}

	public String getSysVersion() {
		return sharedPref.getString("sysVersion", "");
	}

	public String getAppVersion() {
		return sharedPref.getString("appVersion", "");
	}

	public String getChannel() {
		return sharedPref.getString("channel", "");
	}

	public String getVersion(){
		return sharedPref.getString("version", "");
	}

	private TokenHeaderHelper() {

	}

	private static class Singleton {
		static TokenHeaderHelper INSTANCE = new TokenHeaderHelper();
	}

	public static TokenHeaderHelper get() {
		return Singleton.INSTANCE;
	}

	public TokenHeaderHelper init(Context context) {
		if (sharedPref == null) {
			sharedPref = context
					.getSharedPreferences(TOKEN_VALUE_FILE, Context.MODE_PRIVATE);
		}
		if (packageInfo == null) {
			packageInfo = getPackageInfo(context);
		}
		String deviceModel = Build.BRAND + "|" + Build.MODEL;
		String sysVersion = Build.VERSION.SDK_INT + "";
		String appVersion = packageInfo.versionName;
		String channel = "channel_shikee";
		String deviceVersion = "1.0.0";
//		try {
//			appInfo = MyApplication.getInstance().getPackageManager()
//					.getApplicationInfo(MyApplication.getInstance().getPackageName(),
//							PackageManager.GET_META_DATA);
//			String data_name = appInfo.metaData.getString("UMENG_CHANNEL");
//			if (!TextUtils.isEmpty(data_name)) {
//				channel = data_name;
//			}
//		} catch (PackageManager.NameNotFoundException e) {
//		}
		//String deviceId = getCountDeviceId();
		String deviceId = getMacAddr();
//		deviceVersion = AppUtils.getAppVersionName();
		saveHeaderInfo(deviceId, deviceModel, sysVersion, appVersion, channel,deviceVersion);
		return this;
	}

	private PackageInfo getPackageInfo(Context context) {
		PackageInfo pi = null;
		try {
			PackageManager pm = context.getPackageManager();
			pi = pm.getPackageInfo(context.getPackageName(),
					PackageManager.GET_CONFIGURATIONS);
			return pi;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return pi;
	}

	private String getCountDeviceId() {
		String m_szDevIDShort = "35" + //we make this look like a valid IMEI
				Build.BOARD.length() % 10 +
				Build.BRAND.length() % 10 +
				Build.CPU_ABI.length() % 10 +
				Build.DEVICE.length() % 10 +
				Build.DISPLAY.length() % 10 +
				Build.HOST.length() % 10 +
				Build.ID.length() % 10 +
				Build.MANUFACTURER.length() % 10 +
				Build.MODEL.length() % 10 +
				Build.PRODUCT.length() % 10 +
				Build.TAGS.length() % 10 +
				Build.TYPE.length() % 10 +
				Build.USER.length() % 10; //13 digits
		return m_szDevIDShort;
	}

	public static String getWifiMac(Context ctx) {
		WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		String str = info.getMacAddress();
		if (str == null || str.contains("02:00:00:00:00:00"))
			str = getMac();
		return str;
	}

	/**
	 * 这是使用adb shell命令来获取mac地址的方式
	 * @return
	 */
	public static String getMac() {
		String macSerial = null;
		String str = "";

		try {
			Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
			InputStreamReader ir = new InputStreamReader(pp.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);

			for (; null != str; ) {
				str = input.readLine();
				if (str != null) {
					macSerial = str.trim();// 去空格
					break;
				}
			}
		} catch (IOException ex) {
			// 赋予默认值
			ex.printStackTrace();
		}
		return macSerial;
	}

	public static String getMacAddr() {
		try {
			List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface nif : all) {
				if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

				byte[] macBytes = nif.getHardwareAddress();
				if (macBytes == null) {
					return "";
				}

				StringBuilder res1 = new StringBuilder();
				for (byte b : macBytes) {
					res1.append(String.format("%02X:",b));
				}

				if (res1.length() > 0) {
					res1.deleteCharAt(res1.length() - 1);
				}
				return res1.toString();
			}
		} catch (Exception ex) {
		}
		return getMac();
	}
}
